<?php
/**
 * Page for ordering print on demand resources
 *
 * @copyright &copy; 2006 The Open University
 * @author D.A.Woolhead@open.ac.uk
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package resourcepage
 */

require_once(dirname(__FILE__).'/../../config.php');
require_once(dirname(__FILE__).'/extensions/etexts/etexts.php');

// Pick up course module id for returning to when continue
$id = optional_param('id',0,PARAM_INT); // Course Module Id
if (empty($id)) {
    error('Access Denied');
}

// Get course modules record
if (!$cm = get_coursemodule_from_id('resourcepage', $id)) {
    error('Course Module ID was incorrect');
}

// Get course record
if (!$course = get_record('course', 'id', $cm->course)) {
    error('Course is misconfigured');
}

// Get course module table name/type field
if (!$cmtype = get_field('modules', 'name', 'id', $cm->module)) {
    error('Course is misconfigured');
}

// Get course module type instance name
if (!$cmname = get_field($cmtype, 'name', 'id', $cm->instance)) {
    error('Course is misconfigured');
}

// Pick up optional document to be added to order
$addtoorder = optional_param('addtoorder',NULL,PARAM_ALPHA); // Add to Order
$filename = trim(optional_param('filename','',PARAM_FILE)); // Document to print
$title = trim(optional_param('title','',PARAM_CLEAN)); // Title of document to print

// Pick up optional document to be removed from order
$remove = optional_param('remove',NULL,PARAM_FILE); // Remove from Order

// Pick up optional order submission
$confirmorder = optional_param('confirmorder',NULL,PARAM_ALPHA); // Confirm Order

// Pick up optional name and address
$name = trim(optional_param('name','',PARAM_CLEAN)); // Name
if (empty($name)) {
    $name = isset($USER->firstname) ? $USER->firstname : '';
    $name .= isset($USER->lastname) ? ' '.$USER->lastname : '';
}

$address1 = trim(optional_param('address1','',PARAM_CLEAN)); // Address 1
$address2 = trim(optional_param('address2','',PARAM_CLEAN)); // Address 2
$address3 = trim(optional_param('address3','',PARAM_CLEAN)); // Address 3
$town = trim(optional_param('town','',PARAM_CLEAN)); // Town/City
$county = trim(optional_param('county','',PARAM_CLEAN)); // County/State
$postcode = trim(optional_param('postcode','',PARAM_CLEAN)); // PostCode

$country = trim(optional_param('country','',PARAM_CLEAN)); // Country
if (empty($country)) {
    $country = 'United Kingdom';
}

// Pick up optional array of items to be ordered
$orderitems = isset($_SESSION['orderitems']) ? $_SESSION['orderitems'] : array();

// Check for Confirm Order button clicked
if (isset($confirmorder)) {

    // Print Heading for order confirmation
    $navigation = build_navigation(array(array('name' => 'Order Confirmation', 'link' => '', 'type' => 'title')), $cm);
    print_header(strip_tags($SITE->fullname), $SITE->fullname, $navigation);

    $address = $address1."\n".$address2."\n".$address3."\n".$town."\n".$county."\n".$postcode."\n".$country;
    $addressx = $address1; // Mandatory address line 1
    $addressx .= $address2 ? "\n".$address2 : ''; // Optional address line 2
    $addressx .= $address3 ? "\n".$address3 : ''; // Optional address line 3
    $addressx .= $town ? "\n".$town : ''; // Mandatory Town/City (but check for no address at all)
    $addressx .= $county ? "\n".$county : ''; // Optional County/State
    $addressx .= $postcode ? "\n".$postcode : ''; // Optional PostCode
    $addressx .= $country ? "\n".$country : ''; // Mandatory Country (but check for no address at all)

    $errmsg = '';
    $errmsg .= $name ? '' : '<li>No name has been entered.</li>';
    if (!$addressx) {
        $errmsg .= '<li>No postal address has been entered.</li>';
    } else {
        $errmsg .= $address1 ? '' : '<li>An incomplete postal address has been entered.  ' .
                                 'You must enter something in the first address field.</li>';
        $errmsg .= $town ? '' : '<li>An incomplete postal address has been entered.  ' .
                                 'You must enter something in the town/city field.</li>';
        $errmsg .= strpos($addressx, "@") === false ? '' : '<li>No postal address has been entered.  ' .
                                                          'Email delivery is not available.</li>';
    }

    $errmsg .= count($orderitems) ? '' : '<li>No document(s)</li>';

    if (empty($USER->username)) {
        $errmsg .= '<li>Who?</li>';
    } else {
        $ordername = $USER->username;
    }

    if ($errmsg) {

        // Form validation error, Display message
        print "
<p>The following errors have been found in your form entry:</p>
<ul>$errmsg</ul>
<p>Please correct them, then submit your order again.</p>";
    } else {

        // Form validated successfully
        $cudosItems = "";
        $printorder=$displaydocs=$logstring="";
        $cudosNumber = 0;
        foreach ($orderitems as $filename => $title) {

            // Determine supcode for item
            $matches = array();
            if (preg_match(resourcepage_etexts::MATCH_WEB, $filename, $matches)) {
                $supcode = 'WEB'.$matches[1];
            } else if (preg_match(resourcepage_etexts::MATCH_ISBN, $filename, $matches)) {
                if (strlen($matches[1]) == 13) {
                    $supcode = 'N'.$matches[1];
                } else {
                    $supcode = 'ISBN'.$matches[1];
                }
            } else if (preg_match(resourcepage_etexts::MATCH_SUP, $filename, $matches)) {
                $supcode = 'SUP'.$matches[1];
            } else {
                $supcode = $filename;
            }

            $displaydocs.=htmlspecialchars($title)."<br>";
            $printorder.=$title."(".$supcode.")\n\n";
            $logstring.=$title."(".$supcode.");";
            $cudosNumber++;
            $cudosCode = strtoupper(trim(str_replace(".pdf","",$supcode)));
            $cudosItems.="^LineStart^".$cudosNumber."^~\r\n^ProductCode^".$cudosCode.
                         "^~\r\n^ProductQuantity^1^~\r\n^LineEnd^".$cudosNumber."^~\r\n";
        }
        print "
<p>The following documents:</p>
<p><strong>$displaydocs</strong></p>
<p>will be sent to:</p>";
        $addressdisplay=str_replace("\n","<br/>",htmlspecialchars($addressx));
        print "<p><strong>$name<br/>$addressdisplay</strong></p>";
        $printorderstring="please send:\n\n$name\n$address\n\nthe following documents:\n\n".$printorder."\n\n";

        // generate a (hopefully) unique Order Reference from date, time and oucu
        $date=date('d.m.y');
        $time=date('G:i:s');
        $cudosORef=$date.$time.$ordername;
        // strip punctuation from date & time to get just numbers and letters
        $replacebits=array(":",".");
        $cudosORef=str_replace($replacebits,"", $cudosORef);

        if (strlen($cudosORef)>25) {
            // cudos system limit for Order Ref is 25 chars, so truncate
            $cudosORef = substr($cudosORef, 0, 25);
        }

        $cudosstring = "^OrderStart^^~\r\n^User^ouglobal^~\r\n^OrderRef^" . $cudosORef .
                       "^~\r\n^DeliveryAddress1^".$name."^~\r\n^DeliveryAddress2^".$address1.
                       "^~\r\n^DeliveryAddress3^".$address2."^~\r\n^DeliveryAddress4^".$address3.
                       "^~\r\n^DeliveryAddress5^".$town."^~\r\n^DeliveryAddress6^".$county.
                       "^~\r\n^DeliveryPostalCode^".$postcode."^~\r\n^DeliveryCountry^".$country.
                       "^~\r\n". $cudosItems . "^OrderEnd^^";

        $subject = "AUTOEMAILORDER REF " . $ordername . " " . $date . " " . $time;

        global $CFG;
        $emails = array();
        if (!empty($CFG->printondemandemailto)) {
            $emails = explode(' ', $CFG->printondemandemailto);
        }

        if (empty($emails)) {

            // No email addresses configured, Display message
            print '<p><strong>Documents will not actually be sent.</strong> No email addresses configured for Print On Demand.</p>';

        } else {
            foreach ($emails as $email) {

                // Use moodle function for sending email(s)
                $userto = new stdClass;
                $userto->id = 0;
                $userto->firstname = '';
                $userto->lastname = '';
                $userto->email = $email;
                if (empty($CFG->printondemandemailfrom)) {
                    $userfrom='';
                } else {
                    $userfrom = new stdClass;
                    $userfrom->id = 0;
                    $userfrom->firstname = '';
                    $userfrom->lastname = '';
                    $userfrom->email = $CFG->printondemandemailfrom;
                    $userfrom->maildisplay = 999;
                }
                email_to_user($userto, $userfrom, $subject, $cudosstring); // derekw
            }
        }
        // Remove all items from order
        $orderitems = array();
        $_SESSION['orderitems'] = $orderitems;

        //log request in database
        //strip commas, apostrophes and returns out of $address for log
        $return = chr(13).chr(10); // this is a line feed
        $findchars = array("\\\"","\'",",","'","\"",$return);
        $name=str_replace($findchars," ",$name);
        $address=str_replace($findchars," ",$address);
        $logstring=str_replace($findchars," ",$logstring);

        add_to_log(0, 'resource', 'print', basename(__FILE__), substr($logstring, 0, 254), $id);

    }
} else {

    // Print Heading for ordering a printed copy
    $navigation = build_navigation(array(array('name' => 'Order a print copy', 'link' => '', 'type' => 'title')), $cm);
    print_header(strip_tags($SITE->fullname), $SITE->fullname, $navigation);
    
    // Check for item to be added to order
    if (isset($addtoorder)) {

        // Add item to order
        $orderitems[$filename] = $title;
        $_SESSION['orderitems'] = $orderitems;

        print '<p><strong>'.htmlspecialchars($title).'</strong> has been added to your print order.</p>';

    // Otherwise check for item to be removed from order
    } else if (isset($remove)) {

        // Remove item from order
        // [Bug 2884] Ignore error if already removed in same session but another window!
        if (!isset($orderitems[key($remove)])) {
            $orderitems[key($remove)] = 'Item';
        }
        $title = $orderitems[key($remove)];
        unset($orderitems[key($remove)]);
        $_SESSION['orderitems'] = $orderitems;
        
        $message='<strong>'.htmlspecialchars($title).'</strong> has been removed from your print order. ';
        if (!count($orderitems)) {
            $message .= "Your print order is now empty.";
        } 
        print "<p>$message</p>";
    }
    if(count($orderitems)) {
        print "
<ul>
<li>To complete the order, enter your full address below and click <strong>Confirm order</strong>.</li>
<li>If you want to add more items, click <strong>Continue</strong> to return to the website.</li>
</ul>";
    }
}

// Display button to return to previous page
?>
    <form method="get" action="view.php">
        <input type="hidden" name="id" value="<?php print $id; ?>" />
        <input type="submit" value="Continue"/>
    </form>
<?php

// Check for order items
if (!count($orderitems)) {

    // No order items - just display message after continue button
    // provided order has not been confirmed
    if (!isset($confirmorder) && !isset($remove)) {
        print '<p>No documents in print order.</p>';
    }

} else {

    // Order items available
    // Sort items by Title
    asort($orderitems);

    // Get list of countries
    $countries = get_list_of_countries();

?>
        <form method="post" action="<?php print $_SERVER['PHP_SELF']; ?>">
            <input type="hidden" name="sesskey" value="<?php print sesskey(); ?>" />
            <input type="hidden" name="id" value="<?php print $id; ?>" />

            <h3>Documents</h3>
            <ul class="pod_list">
<?php
                // Display list of items with option to remove item from order
                foreach ($orderitems as $filename => $title) {
?>
                    <li>
                        <?php print htmlspecialchars($title); ?>
                        <input type="submit" name="remove[<?php print $filename ?>]" value="Remove"/>
                    </li>
<?php
                }
?>
            </ul>
        </form>
        <h3>Personal details</h3>
<?php

    try {
        if (file_exists(dirname(__FILE__).'/nameaddress_form.php')) {
            require_once(dirname(__FILE__).'/nameaddress_form.php');
            $orderclass = 'nameaddress_form';
            $editform = new $orderclass();

            // Get order form fields
            $fields_form = array();
            $fields_form['name'] = $name;
            $fields_form['address1'] = $address1;
            $fields_form['address2'] = $address2;
            $fields_form['address3'] = $address3;
            $fields_form['town'] = $town;
            $fields_form['county'] = $county;
            $fields_form['postcode'] = $postcode;
            $fields_form['country'] = $country;

            // Set hidden field values
            $fields_form['sesskey'] = sesskey();                
            $fields_form['id'] = $id;
            $fields_form['confirmorder'] = 'y';

            // Set form default values
            $editform->set_data($fields_form);

            // display form
            $editform->display();
        } else {
            error('No formslib form description file found for this activity.');
            }

    } catch(Exception $e) {
        error_exception($e,'Failed to display address form: '.$e->getMessage());
    }
}

// Display Page Footer
print_footer();

?>